const _path = _interopRequireDefault(require('path'));
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
module.exports = (EdaApi) => {
  let leftList, rightList, text, emojiStr = '😁';
  const Translate = (() => {
    "use strict";
    return {
      clsConfig: {
        friendList: '#pane-side',
        unread: '#pane-side div[role="listitem"]>div>div>div>div:nth-child(2)>div:nth-child(2)>div[role="gridcell"]>span>div>span[aria-label]',
        dialog: '#main',
        dialogTitle: 'header span[dir="auto"]',
        ipt: 'footer > div.copyable-area div.lexical-rich-text-input>div[role="textbox"][data-lexical-editor="true"]',
        main: 'div.copyable-area>div>div[role="application"][data-tab="8"]',
        leftMsg: 'div.message-in div.copyable-text[data-pre-plain-text]>div:not(.trans-inited)',
        rightMsg: 'div.message-out div.copyable-text[data-pre-plain-text]>div:not(.trans-inited)',
        sendBtn: 'footer button[data-tab="11"]',
        tips: 'footer',
        scrollBtn: 'div[role="button"][data-tab="7"]',
      },
      dialog: document,
      dialogId: "",
      toSendText: "",
      setting: {},
      translating: false,
      isGroup: false,
      init() {
        EdaApi.injectCss(_path.default.join(__dirname, 'webview.css'));
        // EdaApi.injectJs(_path.default.join(__dirname, 'index.js'));
        this.initIpcs();
        this.initClick();
        this.initEnterEvent();
        EdaApi.initWebview({
          position: "afterEnd",
          unreadInfo: {
            unread: this.clsConfig.unread
          },
          methods: {
            getText: this.getText,
            checkGroup: this.checkGroup
          }
        });
        console.log("翻译插件初始化完成。");
      },
      initIpcs() {
        EdaApi.initIpcs({
          "update-settings": data => {
            console.log(data);
            this.setting = EdaApi.getSetting(this.dialogId);
          }
        });
      },
      initClick() {
        let btn = null;
        document.addEventListener('click', e => {
          btn = EdaApi.closest(e.target, ".refresh-btn", 2);
          if (btn) {
            this.clickTrans(e, false);
            return;
          }
          btn = EdaApi.closest(e.target, ".trans-btn", 2);
          if (btn) {
            this.clickTrans(e, true);
            return;
          }
          btn = EdaApi.closest(e.target, this.clsConfig.sendBtn, 5);
          if (btn) {
            if (e.isTrusted) {
              this.sendClick(e);
            }
            return;
          }
          btn = document.querySelector(this.clsConfig.friendList);
          if (btn && btn.contains(e.target)) {
            this.initDialog();
            return;
          }
        }, true);
      },
      initEnterEvent() {
        document.addEventListener('keydown', event => {
          (event.key === 'Enter' || event.key === "NumpadEnter") && !event.shiftKey && this.sendClick(event);
        }, true);
      },
      initDialog() {//初始化对话框
        EdaApi.queryWait({ selector: this.clsConfig.dialog }).then(dialog => {
          this.dialog = dialog || document;
          EdaApi.initDialog({
            dialog: this.dialog,
            cls: {
              title: this.clsConfig.dialogTitle,
              tips: this.clsConfig.tips,
              leftMsg: this.clsConfig.leftMsg,
              rightMsg: this.clsConfig.rightMsg
            }
          }).then(({ dialogId, isGroup, setting }) => {
            console.log(dialogId, isGroup, setting);
            this.dialog = dialog;
            this.dialogId = dialogId;
            this.isGroup = isGroup;
            this.setting = setting;
            EdaApi.queryWait({
              parent: this.dialog,
              selector: this.clsConfig.main
            }).then(view => {
              this.initChatListener(view);
            });
          }).catch(() => {
            EdaApi.showLoading({
              msg: "对话框初始化失败，请切换窗口重试！",
              color: "#f46db4"
            });
          });
        });
      },
      initChatListener(view) {//监听新消息
        this.scrollToBottom();
        view.removeEventListener('DOMNodeInserted', this.onNewMessage);
        view.addEventListener('DOMNodeInserted', this.onNewMessage, true);
      },
      onNewMessage() {//刷新聊天栏 插入翻译
        setTimeout(() => {//必须，否则会死循环
          leftList = this.querySelectorAll(Translate.clsConfig.leftMsg);
          rightList = this.querySelectorAll(Translate.clsConfig.rightMsg);
          leftList && leftList.forEach(item => {
            text = Translate.getText(item);
            if (!item.classList.contains("trans-inited")) {
              EdaApi.initMessage({
                item,
                text,
                isGroup: Translate.isGroup,
                isMe: false
              });
            }
          });
          rightList && rightList.forEach(item => {
            text = Translate.getText(item);
            if (!item.classList.contains("trans-inited")) {
              EdaApi.initMessage({
                item,
                text,
                isGroup: Translate.isGroup,
                isMe: true
              });
            }
          });
        }, 200);
      },
      checkGroup() {
        let el = document.querySelector("#main>header>div:nth-child(2)>div:nth-child(2)>span");
        if (!el) {
          return false;
        }
        let title = el.getAttribute('title');
        if (!title) {
          return false;
        }
        if (
          title.indexOf('群组') > -1 ||
          title.indexOf('您') > -1 ||
          title.indexOf('You') > -1 ||
          title.indexOf('这是社群') > -1 ||
          title.indexOf('click here for group info') > -1 ||
          title.indexOf('公告') > -1 ||
          title.indexOf('只有管理员可以发送消息') > -1
        ) {
          return true;
        }
        return false;
      },
      clickTrans(e, cache) {
        let transBox = EdaApi.getTransBox(e);
        const msgBox = EdaApi.getMessageBox(e);
        if (!transBox || !msgBox) return;
        transBox.innerHTML = '翻译中...';
        if (msgBox.classList.contains('_3QeR3')) {
          //语音
          this.transVoice(msgBox, transBox, cache);
        } else {
          this.transText(msgBox, transBox, cache);
        }
      },
      transVoice(msgBox, transBox, cache) {

      },
      transText(msgBox, transBox, cache) {
        let msg = this.getText(msgBox);
        console.log(msg);
        // const etInfo = EdaApi.filterEtTexts(msg);
        // const ets = etInfo.ets;
        // msg = etInfo.msg;
        if (!msg || EdaApi.isNumber(msg)) {
          EdaApi.showResult(transBox, msg);
          return;
        }
        EdaApi.transText({
          msg,
          isMe: msgBox.classList.contains("is-me"),
          isSend: false,
          cache
        }).then(({ body }) => {
          let result = body.msg || '';
          // result = EdaApi.handleEtText(result, ets);
          if (result) {
            EdaApi.showResult(transBox, this.emojiToImg(result, msgBox));
          } else {
            EdaApi.showResult(transBox, this.emojiToImg("翻译失败！", msgBox));
          }
        });
      },
      getText(msgBox) {
        if (!msgBox) {
          return '';
        }
        let hasEmoji = msgBox.querySelector('.emoji');
        let text = '';
        if (!hasEmoji) {
          let spanEl = msgBox.querySelector('.selectable-text.copyable-text');
          text = spanEl ? spanEl.textContent : '';
        } else {
          let spanEls = msgBox.querySelector('span>span');
          let childNodes = spanEls ? spanEls.childNodes : [];
          let i = 0, child;
          for (i = 0; i < childNodes.length; i++) {
            child = childNodes[i];
            if (child.nodeName == '#text') {
              text += child.textContent;
            } else if (child.nodeName == 'IMG') {
              text += emojiStr;
            }
          }
        }
        return text;
      },
      emojiToImg(str, msgDiv) {
        if (str.indexOf(emojiStr) === -1) {
          return str;
        }
        if (!msgDiv) {
          return str;
        }
        let index = 0;
        const emojis = msgDiv.querySelectorAll('.emoji');
        let regex = new RegExp(emojiStr, 'g');
        const replacedStr = str.replace(regex, () => {
          if (index < emojis.length) {
            let str = `<img draggable="${emojis[index].getAttribute(
              'draggable',
            )}" src="${emojis[index].getAttribute('src')}"  class="${emojis[
              index
            ].getAttribute('class')}" style="${emojis[index].getAttribute(
              'style',
            )}" tabindex="${emojis[index].getAttribute('tabindex')}" />`;
            index++;
            return str;
          } else {
            return '';
          }
        });
        return replacedStr;
      },
      sendClick(e) {
        let inputEl = document.querySelector(this.clsConfig.ipt);
        let msg = this.getIptSendMsg(inputEl);
        // const etInfo = EdaApi.filterEtTexts(msg);
        // const ets = etInfo.ets;
        // msg = etInfo.msg;
        console.log(msg);
        if (!msg) return;
        if (EdaApi.isNumber(msg)) return;
        if (!this.setting.sendTrans) return;
        if (this.isGroup && !this.setting.groupTrans) return;
        if (msg == this.toSendText && inputEl.getAttribute('transleted')) {
          inputEl.removeAttribute('transleted');
          // this.hideOriginalText();
          return;
        }
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
        if (this.translating) return;
        this.translating = true;
        this.changeInputStatus(inputEl, false);
        EdaApi.showLoading({ timeout: -1 });
        this.handleSendMessage(inputEl, msg);
      },
      getIptSendMsg(inputEl) {
        if (!inputEl) {
          return '';
        }
        // 只有表情，没有文字不翻译
        if (!inputEl.querySelector('span.selectable-text.copyable-text')) {
          return '';
        }
        let texts = [], items = inputEl.querySelectorAll('p.selectable-text.copyable-text');
        let len = items.length;
        items && items.forEach((item, index) => {
          item.childNodes && item.childNodes.forEach(child => {
            if (child.classList.contains("copyable-text")) {
              texts.push(child.textContent);
            } else {
              texts.push(emojiStr);
            }
          });
          if (index < len - 1) texts.push("{r}");
        });
        if (0 == texts.length) return "";
        console.log(texts);
        return EdaApi.replaceAllHtml(texts.join("{n}").replace(/{n}{r}{n}/g, "{r}"));
      },
      hideOriginalText() {
        let el = this.dialog.querySelector(".original-text");
        if (el) el.style.display = 'none';
      },
      changeInputStatus(inputEl, enable) {
        let el = inputEl.querySelector('div[role="textbox"][data-tab="10"]');
        if (el) el.setAttribute('contenteditable', enable);
      },
      handleSendMessage(inputEl, msg) {//发送消息
        console.log(msg);
        EdaApi.transText({
          msg,
          isMe: true,
          isSend: true,
          cache: false//输入发送时不查缓存，以免翻译准确性不好
        }).then(({ body }) => {
          let result = body.msg || '';
          // result = EdaApi.handleEtText(result, ets);
          console.log(result);
          if (200 == body.code) {
            let texts, arr = result.split("{r}");
            let items = inputEl.querySelectorAll('p.selectable-text.copyable-text');
            // console.log(arr);
            items.forEach((item, index) => {
              texts = arr[index].split("{n}");
              // console.log(texts);
              item.childNodes && item.childNodes.forEach((child, idx) => {
                if (child.classList.contains("copyable-text")) {
                  // console.log(child, child.childNodes, child, idx);
                  try {
                    child && child.childNodes && child.childNodes[0].textContent && (child.childNodes[0].textContent = texts[idx] || "");
                  } catch (error) {
                  }
                }
              });
            });
            if (this.setting.sendConfirm) {
              this.toSendText = this.getIptSendMsg(inputEl);
              EdaApi.showLoading({
                msg: '翻译成功，确认后再次回车发送',
                color: "#67C23A"
              });
              inputEl.setAttribute('transleted', 1);
            } else {
              let clickTimer = setTimeout(() => {
                let btn = document.querySelector(this.clsConfig.sendBtn);
                btn && btn.click();
                EdaApi.hideLoading();
                clearTimeout(clickTimer);
                clickTimer = null;
              }, 10);
            }
            this.translating = false;
            this.changeInputStatus(inputEl, true);
          } else {
            this.translating = false;
            this.changeInputStatus(inputEl, true);
            EdaApi.showLoading({
              msg: result,
              color: "#f46db4"
            });
          }
        });
      },
      scrollToBottom() {
        EdaApi.queryWait({ selector: this.clsConfig.scrollBtn, parent: this.dialog }).then(btn => {
          btn && btn.click();
        });
      }
    }
  })();
  Translate.init();
};